//
//  XJSelectStandardsView.m
//  XinJiangMall
//
//  Created by RaoBo on 2018/5/9.
//  Copyright © 2018年 Tzyang. All rights reserved.
//  Standards: 标准、规格
//  选择规格view

#import "XJSelectStandardsView.h"
// View
#import "XJFeatureItem.h"
#import "XJFeatureSectionHeaderView.h"
#import "XJBuyInfoTableViewCell.h" // cell
#import "XJBuyNumView.h" // 加减按钮

// Modes
#import "XJFeatureItemModel.h"
#import "XJFeatureSectionItemModel.h"
#import "XJStockModel.h"
#import "XJBuyInfoModel.h" // 头部商品信息Model



// Vendors
#import "DCCollectionHeaderLayout.h"

static NSString *const XJFeatureItemReuseId = @"XJFeatureItemReuseId";
static NSString *const XJFeatureSecHeaderReuseId= @"XJFeatureSecHeaderReuseId";
static NSString *const XJBuyInfoTableViewCellId = @"XJBuyInfoTableViewCellId";


@interface XJSelectStandardsView()<HorizontalCollectionLayoutDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UITableViewDataSource,UITableViewDelegate,XJBuyCountDelegate>
@property(nonatomic, strong) UIView *whiteBgView; //白色背景view. 装其他子控件
@property(nonatomic, strong) UITableView *tableView; //商品信息+购买数量按钮 放在whiteBgView上部
@property(nonatomic, strong) UICollectionView *clv; //选择规格具体信息 放在whiteBgView下部。
@property(nonatomic, strong) UIButton *sureBtn; // 确定按钮 放在clv上


//
/**选中的 item 数据源*/
@property(nonatomic, strong) NSMutableArray *selectedArr;

/**商品信息model*/
@property(nonatomic, strong) XJBuyInfoModel *buyInfoModel;


// 添加购物车要用到的参数
/**记录:购买数量  默认是1 */
@property(nonatomic) NSString * buyCount;
/**记录:选择的规格id*/
@property (nonatomic, copy) NSString *chooseGuiGeId;

/**7-12 用于判断点击的是 加入购物车按钮 还是 立即购买按钮*/
@property (nonatomic, assign) XJSelectStandardsViewBuyType buyType;

@end

@implementation XJSelectStandardsView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
         // 购买数量默认为1:
        self.buyCount = @"1";
        [self setupSubView];
    }
    return self;
}

#pragma mark - 一 lazyload
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:(UITableViewStylePlain)];
//        _tableView.backgroundColor = [UIColor brownColor];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        
        [_tableView registerNib:[UINib nibWithNibName:@"XJBuyInfoTableViewCell" bundle:nil] forCellReuseIdentifier:@"XJBuyInfoTableViewCellId"];
    }
    return _tableView;
}

- (UIView *)whiteBgView {
    if (!_whiteBgView) {
        _whiteBgView = [UIView new];
        _whiteBgView.backgroundColor = [UIColor redColor];
    }
    return _whiteBgView;
}

- (UICollectionView *)clv {
    if (!_clv) {
        DCCollectionHeaderLayout *layout = [DCCollectionHeaderLayout new];
        layout.lineSpacing = 8;
        layout.interitemSpacing = 5;
        layout.headerViewHeight = 40;
        layout.delegate = self;
        
        _clv = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _clv.backgroundColor = [UIColor whiteColor];
        _clv.delegate = self;
        _clv.dataSource = self;
        
        // 注册cell
        [_clv registerClass:[XJFeatureItem class] forCellWithReuseIdentifier:XJFeatureItemReuseId]; // item
        [_clv registerClass:[XJFeatureSectionHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:XJFeatureSecHeaderReuseId]; // headerSection
    }
    
    return _clv;
}
- (UIButton *)sureBtn {
    if (!_sureBtn) {
        _sureBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        [_sureBtn setTitle:@"确定" forState:UIControlStateNormal];
        [_sureBtn setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
        [_sureBtn setTitleColor:[UIColor lightGrayColor] forState:(UIControlStateHighlighted)];
        _sureBtn.backgroundColor = XJCOLOR_RGB(255, 218, 67);
        _sureBtn.layer.masksToBounds = YES;
        _sureBtn.layer.cornerRadius = 15;
        
        [_sureBtn addTarget:self action:@selector(clickSureAction) forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _sureBtn;
}
#pragma mark - 确定按钮
- (void)clickSureAction{
    XJLog(@"确定");
    //整理选择的参数并传递出去。
    NSString *cnt = self.buyCount;
    NSString *shopId = self.buyInfoModel.shop_id;
    NSString *goodsId = self.buyInfoModel.goodsId;
    NSString *guiGeid = self.chooseGuiGeId; // 可选参数
    
    NSDictionary *infoDic = [self chosenGoodsInfoDicWithCnt:cnt shopId:shopId goodsId:goodsId chosenGuigeId:guiGeid];
    
    // 如果有规格 都选中才可进入下一步 再把参数传递出去
    // 如果没有规格。直接进入下一步
    if (self.dataArr.count) { //有规格的情况下必须选择规格才能进行下一步
        if ([NSString isEmptyString:self.chooseGuiGeId]) {
            [MBProgressHUD showError:@"请选择商品规格"];
            return;
        }
    }else { //如果没有规格 直接购买吧。
        XJLog(@"没有规格 直接购买吧。");
    }
    
    // 回调参数
    if (self.clickSureBtnBlock) {self.clickSureBtnBlock(infoDic, _buyType);}
    
    // 视图消失
    [self rb_hideSelectStandardsView];

}

- (NSDictionary *)chosenGoodsInfoDicWithCnt:(NSString *)cnt shopId:(NSString *)shopId goodsId:(NSString *)goodsId chosenGuigeId:(NSString *)guigeId {
    NSMutableDictionary *dicM = [NSMutableDictionary dictionary];
    
    if (![NSString isEmptyString:cnt]) {
        [dicM setValue:cnt forKey:@"quantity"];
    }
    
    if (![NSString isEmptyString:shopId]) {
        [dicM setValue:shopId forKey:@"shop_id"];
    }
    
    if (![NSString isEmptyString:goodsId]) {
        [dicM setValue:goodsId forKey:@"goods_id"];
    }
    
    if (![NSString isEmptyString:@"guigeId"]) {
        [dicM setValue:guigeId forKey:@"option_id"];
    }
    
    return dicM.copy;
}

#pragma mark - 二 UI & 布局
- (void)setupSubView {
    
    self.backgroundColor = XJCOLOR_RGBA(110, 110, 110, 0.8);
    [self addSubview:self.whiteBgView];
    
    self.tableView.frame = CGRectMake(0, 0, KWidth, 150);// 高度固定150。添加到whiteBgView上
    // tableViewfooterView
    XJBuyNumView *footView = [[XJBuyNumView alloc] initWithFrame:CGRectMake(0, 100, KWidth, 50)];
    footView.delegate = self; // 用户获取购买数量。
    self.tableView.tableFooterView = footView;
    
    // 添加子控件到 whiteBgView 上
    [self.whiteBgView addSubview:self.tableView];
    
    [self.whiteBgView addSubview:self.clv];
    [self.whiteBgView addSubview:self.sureBtn];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    // 不写frame 怎么能显示
    self.frame = CGRectMake(0, 0, KWidth, KHeight);
    
    // self 默认设置为灰色半透明
    // whiteBgView作为容器装其他view // 按屏高的比例算。KHeight*0.3
    [self.whiteBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self).offset(KHeight*0.3);
        make.left.equalTo(self);
        make.right.equalTo(self);
        make.bottom.equalTo(self);
    }];
    
    [self.clv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.whiteBgView).offset(150);
        make.left.equalTo(self);
        make.right.equalTo(self);
        make.bottom.equalTo(self);
    }];
    
    // 是添加在self.whiteView上的。
    self.sureBtn.frame = CGRectMake((KWidth-300)/2, KHeight*0.7 - 60, 300, 40);
}

#pragma mark - 三 XJBuyCountDelegate
- (void)xj_buyedCount:(NSInteger)num {
    self.buyCount = [NSString stringWithFormat:@"%ld",(long)num];
    XJLog(@"购买数量是:%ld",num);
}

#pragma mark - 四 UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//    TopTableViewCellId
    XJBuyInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"XJBuyInfoTableViewCellId"];
    
//    cell.textLabel.text = [NSString stringWithFormat:@"%ld",(long)indexPath.row];
    
    cell.buyModel = self.buyInfoModel;
    
    // 点击❎ 隐藏视图
    __weak typeof(self) weakSelf = self;
    cell.xjCancelBlock = ^{
        XJLog(@"");
        [weakSelf rb_hideSelectStandardsView];
    };
    
    // 给cell赋值
    return cell;
}
#pragma mark - 五 UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100; // 固定100
}


#pragma mark - HorizontalCollectionLayoutDelegate
// item宽度自适应
- (NSString *)collectionViewItemSizeWithIndexPath:(NSIndexPath *)indexPath {
    
//    return self.dataArr[indexPath.section].items[indexPath.row].infoname;

    return self.dataArr[indexPath.section].items[indexPath.row].name;
}


#pragma mark - 六 UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
    return self.dataArr.count;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.dataArr[section].items.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    XJFeatureItem *item = [collectionView dequeueReusableCellWithReuseIdentifier:XJFeatureItemReuseId forIndexPath:indexPath];
    
    XJFeatureItemModel *itemM = self.dataArr[indexPath.section].items[indexPath.row];
    
    item.itemModel = itemM;
    
    return item;
}

// 返回section
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        XJFeatureSectionHeaderView *sectionHeaderV = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:XJFeatureSecHeaderReuseId forIndexPath:indexPath];
        
        // 给section 的标题赋值。
        sectionHeaderV.sectionTitleLb.text = self.dataArr[indexPath.section].name;
        
        return sectionHeaderV;
    }else {
        return nil;
    }
}

#pragma mark -  UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    // 确保每个section只有一个被选中
    
    // 获取被点击的item 的 model
    XJFeatureItemModel  *selItemModel = self.dataArr[indexPath.section].items[indexPath.row];
    if (selItemModel.isSelect == NO) {
        NSInteger count = self.dataArr[indexPath.section].items.count;
        
        // isSelect 全设置为NO
        for (int i=0; i<count; i++) {
            self.dataArr[indexPath.section].items[i].isSelect = NO;
        }
    }
    
    // 取反:标记当前点击的item为选中状态
    selItemModel.isSelect = !selItemModel.isSelect;
    
    // 保存选择的规格
    self.selectedArr = @[].mutableCopy;
    for (int i=0; i<self.dataArr.count; i++) {
        for (int j=0; j<self.dataArr[i].items.count; j++) {
            XJFeatureItemModel *selectedItemM  = self.dataArr[i].items[j];
            if (selectedItemM.isSelect == YES) {
                [self.selectedArr addObject:selectedItemM];
            }else {
                [self.selectedArr removeObject:selectedItemM];
            }
        }
    }
    
    XJLog(@"选择的规格是:%@",self.selectedArr);
    
    NSMutableString *choseStr = [NSMutableString string];
    
    for (XJFeatureItemModel *model in self.selectedArr) {
        [choseStr appendFormat:@" %@",model.name];
    }
    
    // 比对判断库存数量:获取要比对的数据
    NSString *specStr = [self append_InTheMiddleSelectedGuiGeArr:self.selectedArr];

    // 遍历库存数组,比对后判断数库存数并刷新
    for (XJStockModel *stockM in self.stockArr) {
        if ([stockM.specs isEqualToString:specStr]) {
            // 对model重新赋值并刷新tableView
            NSLog(@"组合id:%@--库存:%@",stockM.specs,stockM.stock);
            self.buyInfoModel.stock = stockM.stock;
            self.buyInfoModel.chosenStr = choseStr;
            
            // 记录选择的规格id
            self.chooseGuiGeId = stockM.chosenGuiGeId;
            
            [self.tableView reloadData];
            
            break;
        }
    }
    
    // 关键:
    [self.clv reloadData];
}

#pragma mark - 七 Public & 给 XJBuyInfoModel 赋值
- (void)rb_showSelectStandardsViewWithType:(XJSelectStandardsViewBuyType)type{

    _buyType = type; //7-12标记类型
    
    UIWindow *appWindow = [[UIApplication sharedApplication] keyWindow];
    [appWindow addSubview:self];
    
    // ------View出现动画
    self.transform = CGAffineTransformMakeTranslation(0.01, KHeight);
    [UIView animateWithDuration:0.25 animations:^{
        
        self.transform = CGAffineTransformMakeTranslation(0.01, 0.01);
    }];
    
    
    // 给商品信息模型赋值
    NSLog(@"%@",self.buyInfoDic);
    self.buyInfoModel = [XJBuyInfoModel mj_objectWithKeyValues:self.buyInfoDic];
    
    NSLog(@"%@",self.buyInfoModel);
}
//- (void)rb_showSelectStandardsView {
//    UIWindow *appWindow = [[UIApplication sharedApplication] keyWindow];
//    [appWindow addSubview:self];
//
//    // ------View出现动画
//    self.transform = CGAffineTransformMakeTranslation(0.01, KHeight);
//    [UIView animateWithDuration:0.25 animations:^{
//
//        self.transform = CGAffineTransformMakeTranslation(0.01, 0.01);
//    }];
//
//
//    // 给商品信息模型赋值
//    NSLog(@"%@",self.buyInfoDic);
//    self.buyInfoModel = [XJBuyInfoModel mj_objectWithKeyValues:self.buyInfoDic];
//
//    NSLog(@"%@",self.buyInfoModel);
//
//}

- (void)rb_hideSelectStandardsView {
    [UIView animateWithDuration:0.25 animations:^{
        
        self.transform = CGAffineTransformMakeTranslation(0.01, KHeight);
    } completion:^(BOOL finished) {
        
        [self removeFromSuperview];
    }];
}


#pragma mark - 八 工具方法
/**功能: @[137,140] ---> 137_140  有待优化*/
- (NSString *)append_InTheMiddleSelectedGuiGeArr:(NSArray <XJFeatureItemModel *>*)guigeArr {
    
    NSMutableString *resultStr = [NSMutableString string];
    
    
    for (XJFeatureItemModel *model in guigeArr) {
        [resultStr appendFormat:@"_%@",model.guigeId];
        
        XJLog(@"现出原形：%@",model);
    }
    
    if ([resultStr hasPrefix:@"_"]) {
        [resultStr replaceCharactersInRange:NSMakeRange(0, 1) withString:@""];
    }

    return resultStr.copy;
}


#pragma mark - 九 Bug
/**
 bug: 点击屏幕上的任何view都会调用。 怎么拦截。
 点击tableview collectionView不会调用。
 解决：whiteBgView 上中下分别放tableView、clv、btn 这样这个方法就不会触发了
 */
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self rb_hideSelectStandardsView];
}

#pragma mark - 十 业务逻辑说明
/**
 选择规格 分两种情况
 1.有规格 选择规格后才能进行处理
 
 2.没有规格:也得让人家买呀! 规格字段可以为空 so
 2-1 所以你在传递参数的时候,如果没有规格就该怎么处理 接口文档未做说明。https://www.showdoc.cc/web/#/35938840106499?page_id=267834637727357
 抓包的结果是约定为如果没有 对应字段的值直接传0。
 
 2-2 我的处理是:如果没有就不传该字段。
 */

//添加购物车请求参数
/**
 {
 "quantity": "1",
 "option_id": "0",
 "shop_id": "12",
 "goods_id": "110"
 }
 */
@end
